package com.cykj.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.cykj.dto.ResponseDTO;
import com.cykj.entity.AdminDO;
import com.cykj.mapper.AdminMapper;
import com.cykj.service.IAdminService;
import com.cykj.util.BcryptEncodeUtil;
import com.cykj.util.RedisServiceUtil;
import com.cykj.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Program: Mooc-Admin
 * @Package: com.cykj.service.impl
 * @Author: 张俊杰
 * @Create: 2025-07-08 20:45
 * @Description: TODO
 * @Vision: 1.0
 **/
@Service
public class AdminServiceImpl implements IAdminService {

    @Value("${baseUrl}")
    private String baseUrl;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisServiceUtil redisServiceUtil;

    @Autowired
    private BcryptEncodeUtil bcryptEncodeUtil;

    @Override
    public ResponseDTO adminLogin(AdminVO adminVO) {

        if (!adminVO.getCode().equals(redisServiceUtil.get(adminVO.getUnique()))) {
            return new ResponseDTO(2, "验证码错误", null);
        }
        AdminDO admin = adminMapper.adminLogin(adminVO);
        if (admin != null) {

            String adminPassword = admin.getAdminPassword();

            if (!bcryptEncodeUtil.matches(adminVO.getAdminPassword(), adminPassword)) {
                return ResponseDTO.error("登录失败");
            }
            // StpUtil.login(id) 方法利用了 Cookie 自动注入的特性
            StpUtil.login(admin.getAdminId());

            String avatarUrl = baseUrl + admin.getAdminAvatar();

            SaSession session = StpUtil.getSession();
            session.set("roleId", admin.getAdminRole());
            session.set("account", admin.getAdminAccount());
            session.set("userId", admin.getAdminId());
            session.set("avatar",avatarUrl);
            session.set("username", admin.getAdminName());

            return new ResponseDTO(1, "登录成功", null);
        }
        return ResponseDTO.error("登录失败");
    }

    @Override
    public ResponseDTO updatePassword(AdminVO adminVO) {

        String newPassword = bcryptEncodeUtil.encode(adminVO.getAdminPassword());
        adminVO.setAdminPassword(newPassword);

        Integer i = adminMapper.updatePassword(adminVO);
        if (i > 0) {
            return ResponseDTO.effectRow(i);
        }
        return ResponseDTO.error("修改失败");
    }
}
